package org.brownflat.watergate.domain;

import org.brownflat.utils.util.StringTypeConverter;
import org.brownflat.utils.util.TypeConverterFactory;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;

import static java.lang.String.format;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Entity
@Table(name = "wgate_configuration")
public class Configuration extends BaseEntity {

    @Enumerated(EnumType.STRING)
    @Column(name="config_key")
    private ConfigurationKey configurationKey;

    @Column(name="config_value")
    private String configurationValue;

    @Column(name="config_value_type")
    private String valueType;

    public ConfigurationKey getConfigurationKey() {
        return configurationKey;
    }

    public void setConfigurationKey(ConfigurationKey configurationKey) {
        this.configurationKey = configurationKey;
    }

    public String getConfigurationValue() {
        return configurationValue;
    }

    public void setConfigurationValue(String configurationValue) {
        this.configurationValue = configurationValue;
    }

    public String getValueType() {
        return valueType;
    }

    public void setValueType(String valueType) {
        this.valueType = valueType;
    }

    public Class getValueTypeClass() {
        try {
            return Class.forName(valueType);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException(format("Could not find class for %s", valueType));
        }
    }

    public Object getValue() {
        try {
          return TypeConverterFactory.get(Class.forName(valueType)).convert(configurationValue);
        } catch (ClassNotFoundException cnfe) {
            return new StringTypeConverter().convert(configurationValue);
        }
    }
}
